package com.fzj.example.io;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: ObjectStreamDemo
 * date: 2019/11/8 14:30
 * Description: TODO
 *
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class ObjectStreamDemo {
    public static void main(String[] args) {
        File file=new File("D:\\self_domain\\server\\language\\JAVA\\java培训\\java基础\\IO\\serializable.txt");
        Teacher teacher=new Teacher();
        teacher.setAddress("安徽");
        teacher.setName("wang");
        Student student=new Student("fzj","湖北",teacher);
        ObjectOutputStream objectOutputStream = null;
        try {
            if(file.exists()){
                file.getParentFile().mkdir();
                file.createNewFile();
            }
            objectOutputStream=new ObjectOutputStream(new FileOutputStream(file));
            List<Student> students=new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                students.add(student);
            }
            objectOutputStream.writeObject(students);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        ObjectInputStream objectInputStream=null;
        File fileReader=new File("D:\\self_domain\\server\\language\\JAVA\\java培训\\java基础\\IO\\serializable.txt");
        try {
            objectInputStream=new ObjectInputStream(new FileInputStream(file));
            Object t = objectInputStream.readObject();
            ArrayList<Student> st= (ArrayList< Student >) t;
            for (Student stu :
                    st) {
                System.out.println(stu.getTeacher().getName()+":   "+stu.getTeacher().getAddress());
                
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                objectInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
